package com.elli0tt.session;

import com.elli0tt.pojo.Configuration;
import com.elli0tt.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * @author elli0tt
 * @version 1.0
 * @className DefaultSqlSession.java
 * @description SqlSession 默认实现
 * @createTime 2020-08-28 23:13:19
 */
public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        // SimpleExecutor query
        Executor executor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);

        return executor.query(configuration, mappedStatement, params);
    }

    @Override
    public <E> E selectOne(String statementId, Object... params) throws Exception {
        Optional<E> optional = findOne(statementId, params);
        return optional.orElse(null);
    }

    @Override
    public <E> Optional<E> findOne(String statementId, Object... params) throws Exception {
        List<E> list = selectList(statementId, params);
        if (list.size() == 0) {
            return Optional.empty();
        } else if (list.size() == 1) {
            return Optional.of(list.get(0));
        } else {
            throw new IllegalArgumentException("query return too much rows");
        }
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        Executor executor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);

        return executor.update(configuration, mappedStatement, params);
    }

    @Override
    public <T> T getMapper(Class<T> mapperClass) {
        // JDK 动态代理为 Mapper 接口生成代理对象
        Object proxyObject = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 1. 获取 statementId
                        String methodName = method.getName();
                        String className = method.getDeclaringClass().getName();
                        String statementId = className + "." + methodName;
                        // 2. 获取被调用方法的返回值类型
                        Type genericReturnType = method.getGenericReturnType();
                        Class<?> returnType = method.getReturnType();
                        if (genericReturnType instanceof ParameterizedType) {
                            // 如果进行了泛型化
                            if (Collection.class.isAssignableFrom(returnType)) {
                                // 如果返回值是集合类型
                                return selectList(statementId, args);
                            }
                            if (Optional.class.isAssignableFrom(returnType)) {
                                // 如果返回值是 Optional
                                return findOne(statementId, args);
                            }
                            throw new IllegalArgumentException("Unknown Return Type");
                        }
                        if (int.class.equals(returnType) || Integer.class.equals(returnType)) {
                            // 如果返回值时 int
                            return update(statementId, args);
                        }
                        return selectOne(statementId, args);
                    }
                });
        return (T) proxyObject;
    }
}
